package com.ruoyi.web.controller.cs;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.cs.domain.TBackpack;
import com.ruoyi.cs.domain.vo.*;
import com.ruoyi.cs.service.CommonService;
import com.ruoyi.cs.service.ITBackpackService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;

import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 背包信息Controller
 * 
 * @author ruoyi
 * @date 2021-03-25
 */
@Api(tags = {"背包信息管理"})
@RestController
@RequestMapping("/cs/backpack")
@SuppressWarnings("ALL")
public class TBackpackController extends BasicsController
{
    private static final Logger log = LoggerFactory.getLogger(TBoxController.class);
    @Autowired
    private ITBackpackService tBackpackService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TokenService tokenService;

    /**
     * 取回信息统计
     */
    @ApiOperation("取回信息统计")
    @RequestMapping(name="取回信息统计",value="retrieveCount",method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:backpack:retrieveCount')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone",value = "手机号" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "userName",value = "用户名称" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "startTime",value = "开始时间" , dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime",value = "结束时间" , dataType = "String", paramType = "query", required = false),
    })
    public Response<Map<String,BigDecimal>> retrieveCount(String userPhone,String userName,String startTime,String endTime)
    {
        Map<String, BigDecimal> map = tBackpackService.retrieveCount(userPhone, userName,startTime, endTime);
        return Response.success(map);
    }

    /**
     * 取回信息列表
     */
    @ApiOperation("取回信息列表")
    @RequestMapping(name="取回信息列表",value="listBack",method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:backpack:listBack')")
    public ResponsePageInfo<TBackPackVo> listBack(@RequestBody TBackPackVo tBackPackVo)
    {
        startPage(tBackPackVo.getPageNum(),tBackPackVo.getPageSize());
        List<TBackPackVo> list = tBackpackService.tBackpackListBack(tBackPackVo);
        return toResponsePageInfo(list);
    }

    /**
     * 人工确认发货状态
     */
    @ApiOperation("人工确认发货状态")
    @PreAuthorize("@ss.hasPermi('cs:backpack:audit')")
    @RequestMapping(name="人工确认发货状态",value="confirmShipment",method = RequestMethod.GET)
    @Log(title = "人工确认发货状态", businessType = BusinessType.OTHER)
    public Response confirmShipment(String bbId,String type){
        return  tBackpackService.confirmShipment(bbId,type);
    }

    /**
     * 人工审核
     */
    @ApiOperation("修改背包状态")
    @PreAuthorize("@ss.hasPermi('cs:backpack:audit')")
    @RequestMapping(name="修改背包状态",value="audit",method = RequestMethod.GET)
    @Log(title = "人工审核", businessType = BusinessType.AUDIT)
    public Response audit(String bbId,String auditStatus,String delivery){
        return  tBackpackService.audit(bbId, auditStatus,delivery);
    }

    /**
     * 获取取回设置详情
     * @param bbId
     * @param auditStatus
     * @return
     */
    @ApiOperation("获取取回设置详情")
    @PreAuthorize("@ss.hasPermi('cs:backpack:retrieveSetInfo')")
    @RequestMapping(name="获取取回设置详情",value="retrieveSetInfo",method = RequestMethod.GET)
    public Response<RetrieveSet> retrieveSetInfo(){
        RetrieveSet set = new RetrieveSet();
        set.setGoodsNum( sysDictDataService.selectDictDataById(132L).getDictValue());
        set.setAuditThreshold( sysDictDataService.selectDictDataById(133L).getDictValue());
        set.setMoneyUpperlimit( sysDictDataService.selectDictDataById(134L).getDictValue());
        //set.setLossUpperlimit( sysDictDataService.selectDictDataById(135L).getDictValue());
        return Response.success(set);
    }
    /**
     * 取回设置
     * @param bbId
     * @param auditStatus
     * @return
     */
    @ApiOperation("取回设置")
    @PreAuthorize("@ss.hasPermi('cs:backpack:retrieveSet')")
    @RequestMapping(name="取回设置",value="retrieveSet",method = RequestMethod.POST)
    @Log(title = "取回设置", businessType = BusinessType.UPDATE)
    public Response retrieveSet(@RequestBody RetrieveSet retrieveSet){
        sysDictDataService.updateValue( retrieveSet.getGoodsNum(),"132");
        sysDictDataService.updateValue( retrieveSet.getAuditThreshold(),"133");
        sysDictDataService.updateValue( retrieveSet.getMoneyUpperlimit(),"134");
        //sysDictDataService.updateValue( retrieveSet.getLossUpperlimit(),"135");
        return  Response.success();
    }

    /**
     * 背包 饰品详细信息
     */
    @ApiOperation("背包 饰品详细信息")
    @RequestMapping(name="背包 饰品详细信息",value="getInfo",method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:backpack:getInfo')")
    @ApiImplicitParam(name = "bbId",value = "背包ID" ,dataType = "String", paramType = "query", required = true)
    public Response<TGoodsBackVo> getInfo(String bbId)
    {
        return Response.success(tBackpackService.selectTBackpackById(bbId));
    }

    /**
     * 修改背包状态
     */
    @PreAuthorize("@ss.hasPermi('cs:backpack:edit')")
    @ApiOperation("修改背包状态")
    @RequestMapping(name="修改背包状态",value="edit",method = RequestMethod.POST)
    @Log(title = "背包信息", businessType = BusinessType.UPDATE)
    public Response edit(@RequestBody TBackpack tBackpack)
    {
        try {
            return tBackpackService.updateTBackpack(tBackpack);
        } catch (Exception e) {
            log.error("修改背包信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 后台赠送饰品
     */
    @PreAuthorize("@ss.hasPermi('cs:backpack:backGiveGoods')")
    @ApiOperation("后台赠送饰品")
    @RequestMapping(name="后台赠送饰品",value="backGiveGoods",method = RequestMethod.POST)
    @Log(title = "后台赠送饰品", businessType = BusinessType.INSERT)
    public Response<String> backGiveGoods(@RequestBody GiveGoodsVo giveGoodsVo)
    {
        return tBackpackService.backGiveGoods(giveGoodsVo);
    }

    /**
     * 取消订单
     */
    @ApiOperation("取消订单")
    @PreAuthorize("@ss.hasPermi('cs:backpack:buyerCancel')")
    @PutMapping("/buyerCancel/{bbId}")
    @Log(title = "取消订单", businessType = BusinessType.AUDIT)
    public Response buyerCancel(@PathVariable("bbId")String bbId){
        return  tBackpackService.buyerCancel(bbId);
    }


    /*---------------------------------------------前端接口-----------------------------------*/
    /**
     * 我的背包信息
     */
    @ApiOperation("web我的背包信息")
    @RequestMapping(name="我的背包信息",value="myBackPack",method = RequestMethod.POST)
    public ResponsePageInfo<TBackpack> myBackPack(@RequestBody PageInfoParamVo pageInfoParamVo)
    {
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userId = sysUser.getLoginUserId();
        TBackPackVo tBackpack = new TBackPackVo();
        tBackpack.setGoodsName(pageInfoParamVo.getGoodsName());
        tBackpack.setUserId(userId);
        tBackpack.setMinPrice(pageInfoParamVo.getMinPrice());
        tBackpack.setMaxPrice(pageInfoParamVo.getMaxPrice());
        String sb = "";
        if (StringUtils.isEmpty(pageInfoParamVo.getSort())) {
            sb = " a.create_time desc";
        }else if("0".equals(pageInfoParamVo.getSort())) {
            sb = " a.goods_price ";
        }else {
            sb = " a.goods_price desc";
        }
        tBackpack.setDelFlag(Constants.SUCCESS);
        startPage(pageInfoParamVo.getPageNum(),pageInfoParamVo.getPageSize(),sb);
        List<TBackpack> list = tBackpackService.getMyTBackpack(tBackpack);
        return toResponsePageInfo(list);
    }

    /**
     * 游戏记录
     */
    @ApiOperation("游戏记录")
    @RequestMapping(name="游戏记录",value="gameRecord",method = RequestMethod.POST)
    public Response<List<TBackpack>> gameRecord(@RequestBody PageInfoParamVo pageInfoParamVo)
    {
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userId = sysUser.getLoginUserId();
        TBackPackVo tBackpack = new TBackPackVo();
        tBackpack.setGoodsName(pageInfoParamVo.getGoodsName());
        tBackpack.setUserId(userId);
        tBackpack.setMinPrice(pageInfoParamVo.getMinPrice());
        tBackpack.setMaxPrice(pageInfoParamVo.getMaxPrice());
        tBackpack.setDelFlag(Constants.SUCCESS);
        List<TBackpack> list = tBackpackService.gameRecord(tBackpack);
        return Response.success(list);
    }

    /**
     * 轮播开箱信息列表
     */
    @ApiOperation("轮播开箱信息列表")
    @RequestMapping(name="轮播开箱信息列表",value="common/carouselList",method = RequestMethod.GET)
    @Cacheable(value="tenSecondsCache", key="'carouselList'")
    public Response<List<GoodsBelongingVo>> carouselList()
    {
        List<GoodsBelongingVo> list = tBackpackService.carouselList();
        return Response.success(list);
    }

    @CheckSwitch
    @ApiOperation("饰品兑换")
    @RequestMapping(name="饰品兑换",value="exchangeGoogs",method = RequestMethod.POST)
    @Log(title = "饰品兑换", businessType = BusinessType.OTHER)
    public Response exchangeGoogs(
            @ApiParam(name = "bbIds", value = "背包ID数组", required = true)
            @RequestBody List<String> bbIds)
    {
        try {
            String userId = tokenService.getLoginUserId();
            return tBackpackService.exchangeGoogs(userId,bbIds);
        } catch (Exception e) {
            log.error("饰品兑换异常:{}",e);
            return Response.fail(Constants.FAILCODE,e.getMessage());
        }
    }

    @ApiOperation("我的取回详情")
    @RequestMapping(name="我的取回详情",value="myRetrieveList",method = RequestMethod.POST)
    public ResponsePageInfo<TBackpack> myRetrieveList(@RequestBody PageInfoParamVo pageInfoParamVo)
    {
        String userId = tokenService.getLoginUserId();
        startPage(pageInfoParamVo.getPageNum(),pageInfoParamVo.getPageSize());
        List<TBackpack> list = tBackpackService.retrieveList(userId,pageInfoParamVo.getGoodsName());
        return toResponsePageInfo(list);
    }

    @CheckSwitch
    @ApiOperation("批量取回")
    @RequestMapping(name="批量取回",value="batchRetrieve",method = RequestMethod.POST)
    @Log(title = "批量取回", businessType = BusinessType.OTHER)
    public Response batchRetrieve(
            @ApiParam(name = "bbIds", value = "背包ID数组", required = true)
            @RequestBody List<String> bbIds)
    {
        try {
            String userId = tokenService.getLoginUserId();
            return  tBackpackService.batchRecaption(bbIds,userId);
        }catch (Exception e){
            log.error("批量取回饰品异常:{}",e);
            return Response.fail(Constants.FAILCODE,e.getMessage());
        }
    }

    @ApiOperation("获取开箱前40条数据")
    @RequestMapping(name = "获取开箱前40条数据", value = "common/backPackopenBoxTopForty", method = RequestMethod.GET)
    @ApiImplicitParam(name = "boxId",value = "箱子ID" ,dataType = "String", paramType = "query", required = true)
    public Response<List<TBackpackOpenBoxTopFortyVo>> selectBackPackTopForty(String boxId) {
        List<TBackpackOpenBoxTopFortyVo> tBackpacks = tBackpackService.backPackopenBoxTopForty(boxId);
        return Response.success(tBackpacks);
    }

    @ApiOperation("轮播列表top3")
    @RequestMapping(name="轮播列表top3",value="common/carouselListTop3",method = RequestMethod.GET)
    @Cacheable(value="tenSecondsCache", key="'carouselListTop3'")
    public Response<List<GoodsBelongingVo>> carouselListTop3()
    {
        List<GoodsBelongingVo> list = tBackpackService.carouselListTop3();
        return Response.success(list);
    }

    @CheckSwitch
    @ApiOperation("退回背包")
    @PutMapping("/return_backpack/{bbId}")
    @Log(title = "手动退回背包", businessType = BusinessType.OTHER)
    public Response returnBackPack(@PathVariable("bbId") String bbId){
        String userId = tokenService.getLoginUserId();
        return tBackpackService.returnBackPack(bbId,userId);
    }
}
